package com.hua.api.modules.finance.rest;

import com.alipay.api.AlipayApiException;
import com.hua.api.core.constants.Status;
import com.hua.api.core.framework.annotation.AnonymousAccess;
import com.hua.api.core.framework.annotation.TokenCheck;
import com.hua.api.core.framework.util.Result;
import com.hua.api.core.framework.util.exception.ApiError;
import com.hua.api.modules.finance.service.AliPayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/alipay")
public class AliPayController {

    private final AliPayService aliPayService;

    /**
     * 付款回调通知
     * */
    @AnonymousAccess
    @ResponseBody
    @RequestMapping("/notify")
    public String alipayNotify(@RequestParam Map<String,String> map){
        log.info("/api/alipay/notify");
        for (Map.Entry<String,String> entry:map.entrySet()) {
            log.info("AliPayController.alipayNotify key={},value={}",entry.getKey(),entry.getValue());
        }
        aliPayService.alipayNotify(map);
        return "success";
    }

    /**
     * 付款状态查询
     * */
    @ResponseBody
    @TokenCheck(userAgent = "tradeQuery", source = {Status.admin,Status.store})
    @RequestMapping("/trade/query/{outTradeNo}")
    public Result tradeQuery(@PathVariable String outTradeNo){
        return Result.of(aliPayService.tradeQuery(outTradeNo));
    }

    /**
     * 付款统一下单
     * */
    // @AnonymousAccess
    @ResponseBody
    @RequestMapping("/trade/precreate/{outTradeNo}")
    @TokenCheck(userAgent = "tradePrecreate", source = {Status.admin,Status.store})
    public Result alipayPreCreate(@PathVariable String outTradeNo){
        log.info("AliPayController.alipayPreCreate outTradeNo={}",outTradeNo);
        try {
            return Result.of(aliPayService.alipayPreCreate(outTradeNo)) ;
        } catch (AlipayApiException e) {
            return Result.error(ApiError.Type.LOGIC_ERROR.toException(e.getMessage()));
        }
    }

    /**
     * app付款统一下单
     * */
    @ResponseBody
    @RequestMapping("/app/precreate/{outTradeNo}")
    @TokenCheck(userAgent = "appPrecreate", source = {Status.admin,Status.store})
    public Result appPrecreate(@PathVariable String outTradeNo){
        log.info("AliPayController.alipayPreCreateApp outTradeNo={}",outTradeNo);
        return Result.of(aliPayService.alipayPreCreateApp(outTradeNo));
    }


}
